// Widgets/Home/AirPackage/AirPackage.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryTravelItem , queryTravelCity } from '../../../api/travel';
var pinyin = require("../../../utils/pinyin.js")
Component({
  options: {
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    origin: '', // 出发地
    destination: '', // 目的地
    journeyDate: '',
    peopleNum: '游玩人数',
    showJourneyPop: false,
    showPeopleNumPop: false,
    adultNum: 1, // 成人人数
    childNum: 0, // 儿童人数
    infantNum: 0, // 婴儿人数
    dataList: [],
    page: 0,
    isReachBottom: false,
    noMore: false,
    loading: false,
    loadingFailed: false,
    cityList: [],
    showCityPop: false,
    type: '1', // 1：出发地，2：目的地
  },
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      this.updateJourneyDate();
      this.getData();
      this._queryTravelCity();
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    updateJourneyDate(){
      var date = wx.getStorageSync('journeyDate');
      if(!date){
        var nowDate = new Date();
        var nowMonth = nowDate.getMonth() + 1;
        var nowDay = nowDate.getDate();
        date = `${nowMonth}月${nowDay}日`;
      }
      console.log(date,'date');
      this.setData({
        journeyDate: date,
      })
    },
    formatDate(date) {
      date = new Date(date);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    // 选择日期
    showJourneyDate(){
      this.setData({showJourneyPop: true});
    },
    // 关闭日期选择
    onJourneyClose(){
      this.setData({showJourneyPop: false});
    },
    // 确认选择日期
    onJourneyConfirm(event){
      this.setData({
        showJourneyPop: false,
        journeyDate: this.formatDate(event.detail),
      })
      wx.setStorageSync('journeyDate', this.formatDate(event.detail))
    },
    // 显示游玩人数
    showPeopleNum(){
      this.setData({showPeopleNumPop: true})
    },
    onPeopleClose(){
      this.setData({showPeopleNumPop: false});
    },
    // 游玩人数切换
    onAdultNumChange(event){
      this.setData({adultNum: event.detail});
      if(this.data.childNum > event.detail * 2 || this.data.infantNum > event.detail){
        if(this.data.childNum > event.detail * 2){
          this.setData({
            childNum: event.detail * 2,
          })
        }else{
          this.setData({
            infantNum: event.detail,
          })
        }
        wx.showToast({
          title: '每名成人最多可携2位儿童和1位婴儿',
          icon: 'none',
        })
      }
      this.setData({
        peopleNum: `${this.data.adultNum}成人${this.data.childNum}儿童${this.data.infantNum}婴儿`
      })
    },
    onChildNumChange(event){
      this.setData({childNum: event.detail});
      this.setData({
        peopleNum: `${this.data.adultNum}成人${this.data.childNum}儿童${this.data.infantNum}婴儿`
      })
    },
    onInfantNumChange(event){
      this.setData({infantNum: event.detail});
      this.setData({
        peopleNum: `${this.data.adultNum}成人${this.data.childNum}儿童${this.data.infantNum}婴儿`
      })
    },
    // 获取机票套餐列表数据
    getData(){
      let _this = this;
      queryTravelItem({itemType: '1',page: _this.data.page,origin: _this.data.origin,destination: _this.data.destination})
      .then(res => {
        if(res.success){
          var list = _this.data.dataList;
          var arr = [];
          for (let index = 0; index < res.data.content.length; index++) {
            const item = res.data.content[index];
            item.title.imageUrlList = item.title.titleImgUrl.split(',');
            console.log(item.title.imageUrlList,'imageUrlList');
            for (let j = 0; j < item.itemInfo.length; j++) {
              const itm = item.itemInfo[j];
              itm.imgUrlList = itm.imgUrl.split(',');
            }
            arr.push(item);
          }
          if(_this.data.page == 0){
            list = arr;
          }else{
            list = list.concat(arr);
          }
          _this.setData({
            dataList: list,
            total: res.data.totalElements,
            page: _this.data.page+1,
          })
          if(_this.data.page * 10 >= res.data.totalElements){
            _this.setData({
              isReachBottom: false,
              noMore: true,
              loading: false,
              loadingFailed: false,
            })
          }else{
            _this.setData({
              isReachBottom: true,
              noMore: false,
              loading: false,
              loadingFailed: false,
            })
          }
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 刷新数据
    onRefresh(){
      this.setData({
        page: 0,
        origin: '',
        destination: '',
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      this.getData();
    },
    // 加载更多
    onLoadMore(){
      if(this.data.isReachBottom){
        this.getData()
      }
    },
    // 跳转详情
    goDetail(e){
      let _this = this;
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      let url = e.target.dataset.name||e.currentTarget.dataset.name;
      wx.navigateTo({
        url: `${url}?item=${JSON.stringify(item)}`,
        events: {
          'updateData': function(){
            _this.onRefresh();
          }
        }
      })
    },
    // 获取城市配置
    _queryTravelCity(){
      let _this = this;
      queryTravelCity({})
      .then(res => {
        if(res.success){
          var cityList = [];
          let i = 0
        /**
         * 1、调用外部js的方法ChineseToPinYin对数据进行分组
         * 2、分组的结果存在排序有误的情况,例如I组,V组等没有汉字的分组
        */
        for (let index = 0; index < res.data.length; index++) {
          const item = res.data[index];
          let bool = cityList.some(ite => {
            return ite.sign == pinyin.ChineseToPinYin(item.city).substr(0, 1)
          })
          if (cityList.length == 0 || !bool) {
            cityList.push({
              id: i,
              sign: pinyin.ChineseToPinYin(item.city).substr(0, 1),
              name: [item]
            })
            i++
          } else if (bool) {
            let a = pinyin.ChineseToPinYin(item.city).substr(0, 1)
            for (let s in cityList) {
              if (a == cityList[s].sign) {
                cityList[s].name.push(item)
              }
            }
          }
        }
        this.setData({
          cityList
        })
        /**
         * 3、对分组好的数据进行排序
         * 4、根据标志sign的ASCII码进行初次排序筛选
         * 5、如果标志sign不在A到Z之间,则添加到#分组中
        */
        this.data.cityList.forEach((item, index) => {
          if ((item.sign.charCodeAt() < 65 || item.sign.charCodeAt() > 90) && item.sign.charCodeAt() != 35) {
            this.data.cityList.splice(index, 1, "")
            // 注:此处为防止splice分割后,数组索引index发生变化,故将需要剔除的元素替换为“”,后再将其剔除
            let i = this.data.cityList.findIndex(item => {
              return item.sign == '#'
            })
            if (i != -1) {
              item.name.forEach(it => {
                this.data.cityList[i].name.push(it)
              })
            } else {
              this.data.cityList.push({
                id: 99,
                sign: '#',
                name: item.name
              })
            }
          }
        })
        // 利用filter方法,剔除之前存在的空元素
        cityList = this.data.cityList.filter(function (s) {
          return s != ''; // 注：IE9(不包含IE9)以下的版本没有trim()方法
        });
        this.setData({
          cityList
        })
        // 利用sort方法进行排序
        this.data.cityList.sort(this.listSort('sign'))
        // 一般情况下#分组在最下面,在此做以处理
        if (this.data.cityList.length > 0 && this.data.cityList[0].sign == '#') {
          this.data.cityList.splice(0, 1).forEach(item => {
            this.data.cityList.push(item)
          })
        }
        this.setData({
          cityList
        })
        console.log(cityList,'cityList');
        }else{
          wx.showToast({
            title: res.errMessage,
            icon: 'none',
          })
        }
      })
    },
    // 排序
    listSort(prop) {
      return function (a, b) {
        var value1 = a[prop].charCodeAt();
        var value2 = b[prop].charCodeAt();
        return value1 - value2
      }
    },
    openCity(e){
      let type = e.target.dataset.type||e.currentTarget.dataset.type;
      this.setData({
        showCityPop: true,
        type: type,
      })
    },
    onCityClose(){
      this.setData({
        showCityPop: false,
      })
    },
    selCity(e){
      let item = e.target.dataset.item||e.currentTarget.dataset.item;
      console.log(item,'item')
      if(this.data.type == '1'){
        this.setData({
          origin: item.city,
          showCityPop: false,
        })
      }
    },
    searchTravel(){
      this.setData({
        page: 0,
        isReachBottom: false,
        noMore: false,
        loading: false,
        loadingFailed: false,
      })
      this.getData();
    },
  }
})